package com.guaju.yueshangLife.activity;

import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.githang.statusbar.StatusBarCompat;
import com.guaju.yueshangLife.BR;
import com.guaju.yueshangLife.R;
import com.guaju.yueshangLife.activity.mine.MyAddressesActivity;
import com.guaju.yueshangLife.activity.mine.OrderDetailActivity;
import com.guaju.yueshangLife.adapter.CaculateGoodsAdapter;
import com.guaju.yueshangLife.adapter.NoneCommonRecyclerViewAdapter;
import com.guaju.yueshangLife.base.MyAppcomActivity;
import com.guaju.yueshangLife.bean.CartGoods;
import com.guaju.yueshangLife.bean.CouponsBean;
import com.guaju.yueshangLife.bean.CreateOrderBean;
import com.guaju.yueshangLife.bean.Goods;
import com.guaju.yueshangLife.bean.MyAddressBean;
import com.guaju.yueshangLife.bean.PrepareOrderBean;
import com.guaju.yueshangLife.databinding.ActivityCaculateBinding;
import com.guaju.yueshangLife.net.ApiEntity;
import com.guaju.yueshangLife.utils.ToastUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

public class CaculateActivity extends MyAppcomActivity {
    public static final int REQUEST_ADDRESS = 188;
    public static final int RESAULT_ADDRESS = 1888;
    public static final String SELECTED_ADDRESS = "address";
    public static final String LIST = "list";
    public static final String TOTAL_COUNT = "total_count";
    public static final String TOTAL_FEE = "total_fee";
    private static final int REQUEST_WRITENOTE = 2001;
    private ActivityCaculateBinding binding;
    private AlertDialog payMethodDialog, selectDiscount;
    private List<String> discount_coupon_lists = new ArrayList();
    private NoneCommonRecyclerViewAdapter<String> stringNoneCommonRecyclerViewAdapter;
    private List<CartGoods> cartGoodsList = new ArrayList<>();
    private String note = "";
    private int addressId = -1;
    private int paymentId = -1;
    private double totalFeeDouble;
    private String postage;
    private List<PrepareOrderBean.DataBean.CouponsBean> coupons;
    private String selectedCouponCode = "";
    int selectPaymethodId = 0;
    String selectPaymethod = "";
    private int selectedCouponPosition;
    private CaculateGoodsAdapter caculateGoodsAdapter;
    private PrepareOrderBean.DataBean.PaymentMethodBean payment_method;
    private ArrayList<Integer> paymethodids = new ArrayList<>();
    private ArrayList<String> payment_method_string = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_caculate);
        StatusBarCompat.setStatusBarColor(this, getResources().getColor(R.color.white));
        setListener();
        updateView();
        initData();

    }

    private void updateView() {
        Intent intent = getIntent();
        cartGoodsList = (List<CartGoods>) intent.getSerializableExtra(LIST);
        totalFeeDouble = intent.getDoubleExtra(TOTAL_FEE, 0);
        int intExtra = intent.getIntExtra(TOTAL_COUNT, 0);
        binding.tvGoodsAmount.setText(intExtra + "件商品");
        String totalFee = "¥" + totalFeeDouble;
        binding.tvGoodsTotalMoney.setText(totalFee);
        binding.tvTotalAmount.setText(totalFee);


        caculateGoodsAdapter = new CaculateGoodsAdapter(CaculateActivity.this);
        caculateGoodsAdapter.setDatas(cartGoodsList);
        caculateGoodsAdapter.setDelivery("快递 免邮");
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(CaculateActivity.this, RecyclerView.HORIZONTAL, false);
        binding.horizontalRecyclerview.setAdapter(caculateGoodsAdapter);
        binding.horizontalRecyclerview.setLayoutManager(linearLayoutManager);

    }

    private void initData() {
        List<Integer> ids = new ArrayList<>();
        for (int i = 0; i < cartGoodsList.size(); i++) {
            CartGoods cartGoods = cartGoodsList.get(i);
            ids.add(cartGoods.getId());
        }
        String str_ids = "[";
        for (Integer id : ids) {
            str_ids += id + ",";
            Log.e("guajujerry", "initData: " + str_ids);
        }
        String substring = str_ids.substring(0, str_ids.length() - 1);
        Log.e("guajujerry", "initData: " + substring);
        str_ids = substring + "]";
        ApiEntity.prepareOrder(str_ids);
        initDiscountData();
        /**
         * 查看是否有默认地址
         */
        ApiEntity.meAddress();
    }

    private void initDiscountData() {
        discount_coupon_lists.add("不使用优惠券");
        stringNoneCommonRecyclerViewAdapter = new NoneCommonRecyclerViewAdapter<String>(this, LayoutInflater.from(this), R.layout.item_dialog_select_discount, BR.discount_name, discount_coupon_lists);
        stringNoneCommonRecyclerViewAdapter.setOnItemClickListener(new NoneCommonRecyclerViewAdapter.OnItemClickListener() {
            @Override
            public void onClick(int position) {
                selectedCouponPosition = position;
                if ((position - 1 >= 0) && (position - 1) < coupons.size()) {
                    selectedCouponCode = coupons.get(position - 1).getCode();

                }
            }
        });
    }

    private void setListener() {
        binding.rlPayMethod.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (payMethodDialog == null) {
                    payMethodDialog = showCommentDailog(R.layout.dialog_pay_method, payment_method_string);

                } else {
                    payMethodDialog.show();
                }
            }
        });

        binding.rlDiscountCoupon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (coupons == null || coupons.isEmpty()) {
                    ToastUtil.show("无可用优惠券");
                } else {
                    if (selectDiscount == null) {
                        selectDiscount = showDiscountDailog(R.layout.dialog_selecte_discount_coupon, coupons);
                    } else {
                        selectDiscount.show();
                    }

                }
            }
        });
        binding.rlLeaveNote.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(CaculateActivity.this, OrderNoteActivity.class);
                startActivityForResult(intent, REQUEST_WRITENOTE);
            }
        });
        FrameLayout fl_back = binding.top.findViewById(R.id.fl_back);
        fl_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        binding.rlAddReceiver.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(CaculateActivity.this, MyAddressesActivity.class);
                startActivityForResult(intent, REQUEST_ADDRESS);
            }
        });
        binding.addressContainer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(CaculateActivity.this, MyAddressesActivity.class);
                startActivityForResult(intent, REQUEST_ADDRESS);
            }
        });
        binding.submitOrder.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                List<Integer> ids = new ArrayList<>();
                for (int i = 0; i < cartGoodsList.size(); i++) {
                    CartGoods cartGoods = cartGoodsList.get(i);
                    ids.add(cartGoods.getId());
                }
                String str_ids = "[";
                for (Integer id : ids) {
                    str_ids += id + ",";
                }
                String substring = str_ids.substring(0, str_ids.length() - 1);
                str_ids = substring + "]";

                if (-1 == addressId) {
                    ToastUtil.show("请选择收货地址");
                    return;
                }
                if (-1 == paymentId) {
                    ToastUtil.show("请选择支付方式");
                    return;
                } else {
                    ApiEntity.creatOrder(str_ids, note, addressId, paymentId, postage);
                }

            }
        });

    }

    private AlertDialog showDiscountDailog(int resId, final List<PrepareOrderBean.DataBean.CouponsBean> coupons) {
        //R.style.***一定要写，不然不能充满整个屏宽，引用R.style.AppTheme就可以
        final int checkedId = 0;
        final AlertDialog dialog = new AlertDialog.Builder(this, R.style.BottomDialog).create();
        View view = View.inflate(this, resId, null);
        if (resId == R.layout.dialog_selecte_discount_coupon) {
            FrameLayout fl_close = view.findViewById(R.id.fl_close);
            Button bt_select_discount_done = view.findViewById(R.id.bt_select_discount_done);
            RecyclerView rv_use_discount = view.findViewById(R.id.rv_use_discount);
            //设置数据
            rv_use_discount.setLayoutManager(new LinearLayoutManager(this));
            DividerItemDecoration itemDecoration = new DividerItemDecoration(this,
                    LinearLayoutManager.VERTICAL);
            rv_use_discount.addItemDecoration(itemDecoration);
            int size = coupons.size();
            for (int i = 0; i < size; i++) {
                PrepareOrderBean.DataBean.CouponsBean couponsBean = coupons.get(i);
                String name = couponsBean.getName();
                discount_coupon_lists.add(name);
            }
            rv_use_discount.setAdapter(stringNoneCommonRecyclerViewAdapter);
            fl_close.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    selectDiscount.dismiss();
                }
            });
            bt_select_discount_done.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (selectedCouponPosition == 0) {
                        binding.tvSelecedDiscountCoupon.setText("不使用优惠券");
                    } else {
                        if ((selectedCouponPosition - 1 >= 0) && (selectedCouponPosition - 1) < coupons.size()) {
                            String selectedCouponName = coupons.get(selectedCouponPosition - 1).getName();
                            binding.tvSelecedDiscountCoupon.setText(selectedCouponName);

                        }
                    }
                }
            });
        }


        Window window = dialog.getWindow();
        window.setGravity(Gravity.BOTTOM);
        //设置dialog弹出时的动画效果，从屏幕底部向上弹出
        //window.setWindowAnimations(R.style.dialogStyle);
//        window.getDecorView().setPadding(0, 0, 0, 0);

        //设置dialog弹出后会点击屏幕或物理返回键，dialog不消失
        dialog.setCanceledOnTouchOutside(true);
        dialog.show();
        window.setContentView(view);

        //获得window窗口的属性
        WindowManager.LayoutParams params = window.getAttributes();
        //设置窗口宽度为充满全屏
        params.width = WindowManager.LayoutParams.MATCH_PARENT;//如果不设置,可能部分机型出现左右有空隙,也就是产生margin的感觉
        //设置窗口高度为包裹内容
        params.height = getResources().getDimensionPixelOffset(R.dimen.bottom_dialog_height);
//        params.softInputMode = WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE;//显示dialog的时候,就显示软键盘
        params.flags = WindowManager.LayoutParams.FLAG_DIM_BEHIND;//就是这个属性导致window后所有的东西都成暗淡
        params.dimAmount = 0.5f;//设置对话框的透明程度背景(非布局的透明度)
        //将设置好的属性set回去
        window.setAttributes(params);
        return dialog;

    }


    /**
     * 弹出评论框
     */
    private AlertDialog showCommentDailog(int resId, final List<String> payment_method) {
        //R.style.***一定要写，不然不能充满整个屏宽，引用R.style.AppTheme就可以

        final AlertDialog dialog = new AlertDialog.Builder(this, R.style.BottomDialog).create();
        View view = View.inflate(this, resId, null);
        if (resId == R.layout.dialog_pay_method) {
            final RadioGroup rg = view.findViewById(R.id.rg_pay_method);

            int dp_60 = getResources().getDimensionPixelSize(R.dimen.dp_60);
            int dp_20 = getResources().getDimensionPixelSize(R.dimen.dp_20);
            if (payment_method != null && !payment_method.isEmpty()) {
                for (String bean : payment_method) {
                    RadioButton rb = (RadioButton) getLayoutInflater().inflate(R.layout.itempayradio, rg, false);
                    rb.setBackgroundResource(R.drawable.selector_pay_method);
                    rb.setWidth(dp_60);
                    rb.setWidth(dp_20);
                    rb.setTextSize(10);
                    rb.setChecked(false);
                    rb.setText(bean);
                    rg.addView(rb);
                }
            }

            final int childCount = rg.getChildCount();
            rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(RadioGroup group, int checkedId) {
                    for (int i = 0; i < childCount; i++) {
                        if (group.getChildAt(i).getId() == checkedId) {

                            selectPaymethodId = paymethodids.get(i);
                            selectPaymethod = payment_method_string.get(i);
                        }
                    }
                }
            });

            View submit = view.findViewById(R.id.submit_paymethod);
            submit.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    binding.tvSelectedPaymethod.setText(selectPaymethod);
                    paymentId = selectPaymethodId;
                    payMethodDialog.dismiss();
                }
            });
            FrameLayout fl_close = view.findViewById(R.id.fl_close);
            fl_close.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    payMethodDialog.dismiss();
                }
            });
        }


        Window window = dialog.getWindow();
        window.setGravity(Gravity.BOTTOM);
        //设置dialog弹出时的动画效果，从屏幕底部向上弹出
        //window.setWindowAnimations(R.style.dialogStyle);
//        window.getDecorView().setPadding(0, 0, 0, 0);

        //设置dialog弹出后会点击屏幕或物理返回键，dialog不消失
        dialog.setCanceledOnTouchOutside(true);
        dialog.show();
        window.setContentView(view);

        //获得window窗口的属性
        WindowManager.LayoutParams params = window.getAttributes();
        //设置窗口宽度为充满全屏
        params.width = WindowManager.LayoutParams.MATCH_PARENT;//如果不设置,可能部分机型出现左右有空隙,也就是产生margin的感觉
        //设置窗口高度为包裹内容
        params.height = getResources().getDimensionPixelOffset(R.dimen.bottom_dialog_height);
//        params.softInputMode = WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE;//显示dialog的时候,就显示软键盘
        params.flags = WindowManager.LayoutParams.FLAG_DIM_BEHIND;//就是这个属性导致window后所有的东西都成暗淡
        params.dimAmount = 0.5f;//设置对话框的透明程度背景(非布局的透明度)
        //将设置好的属性set回去
        window.setAttributes(params);
        return dialog;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_ADDRESS) {
            if (data != null) {
                Bundle extras = data.getExtras();
                binding.rlAddReceiver.setVisibility(View.GONE);
                binding.addressContainer.setVisibility(View.VISIBLE);
                MyAddressBean.DataBean dataBean = (MyAddressBean.DataBean) extras.getSerializable(SELECTED_ADDRESS);
                addressId = dataBean.getId();
                binding.addressName.setText(dataBean.getContact_name());
                binding.addressTel.setText(dataBean.getContact_phone());
                binding.addressDetail.setText(dataBean.getAddress());
            }
        } else if (requestCode == REQUEST_WRITENOTE) {
            if (data != null) {
                note = data.getStringExtra("note");
                binding.tvLeaveNoteInfo.setText(note);
                binding.tvLeaveNoteInfo.setTextColor(Color.parseColor("#222222"));
            }
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMyAddress(MyAddressBean myAddressBean) {
        MyAddressBean.DataBean defaultBean = null;
        if (myAddressBean != null) {
            List<MyAddressBean.DataBean> data = myAddressBean.getData();
            if (data != null && !data.isEmpty()) {
                for (MyAddressBean.DataBean bean : data) {
                    if (bean.getIs_default() == 1) {
                        defaultBean = bean;
                    }
                }
                if (defaultBean != null) {
                    addressId = defaultBean.getId();
                    binding.rlAddReceiver.setVisibility(View.GONE);
                    binding.addressContainer.setVisibility(View.VISIBLE);
                    binding.addressName.setText(defaultBean.getContact_name());
                    binding.addressTel.setText(defaultBean.getContact_phone());
                    binding.addressDetail.setText(defaultBean.getAddress());
                } else {
                    binding.rlAddReceiver.setVisibility(View.VISIBLE);
                    binding.addressContainer.setVisibility(View.GONE);
                }
            }
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onCreateOrder(CreateOrderBean bean) {
        if (bean != null) {
            int code = bean.getCode();
            CreateOrderBean.DataBean data = bean.getData();
            if (200 == code) {
                Toast.makeText(this, "订单已提交", Toast.LENGTH_SHORT).show();
                if (selectPaymethodId == 0) {
                    Intent intent = new Intent(CaculateActivity.this, OrderPaySuccessOfflineActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putString(OrderPaySuccessOfflineActivity.ORDER_NUMBER, data.getOrder_number());
                    bundle.putInt(OrderPaySuccessOfflineActivity.TOTAL_AMOUNT, data.getTotal_amount());
                    bundle.putString(OrderPaySuccessOfflineActivity.TOTAL_FEE, data.getTotal_account());

                    bundle.putInt(OrderPaySuccessOfflineActivity.ORDER_ID, data.getId());
                    intent.putExtras(bundle);
                    startActivity(intent);
                } else {
                    /**
                     * 其他支付方式
                     */
                    Intent intent = new Intent(CaculateActivity.this, OrderDetailActivity.class);
                    intent.putExtra("order_id", data.getId());
                    startActivity(intent);
                }
                finish();
            } else {
                Toast.makeText(this, "订单提交失败", Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(this, "数据异常", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMyPrepare(PrepareOrderBean orderBean) {
        PrepareOrderBean.DataBean defaultBean = null;

        if (orderBean != null) {
            defaultBean = orderBean.getData();
            List<PrepareOrderBean.DataBean.AddressesBean> addresses = defaultBean.getAddresses();
            coupons = defaultBean.getCoupons();
            PrepareOrderBean.DataBean.InvoiceExampleBean invoice_example = defaultBean.getInvoice_example();
            payment_method = defaultBean.getPayment_method();
            if (payment_method.get_$1() != null) {
                payment_method_string.add(payment_method.get_$1());
                paymethodids.add(1);
            }
            if (payment_method.get_$2() != null) {
                payment_method_string.add(payment_method.get_$2());
                paymethodids.add(2);
            }
            if (payment_method.get_$3() != null) {
                payment_method_string.add(payment_method.get_$3());
                paymethodids.add(3);
            }
            if (payment_method.get_$4() != null) {
                payment_method_string.add(payment_method.get_$4());
                paymethodids.add(4);
            }

            postage = defaultBean.getPostage();
            binding.tvDeliveryMoney.setText(postage);
            List<PrepareOrderBean.DataBean.ProductsBean> products = defaultBean.getProducts();
            String total_account = defaultBean.getTotal_account();

            if (payment_method != null) {
                RadioButton radioButton = (RadioButton) getLayoutInflater().inflate(R.layout.itempayradio, null, false);
            }
            if (coupons == null || coupons.isEmpty()) {
                binding.tvSelecedDiscountCoupon.setText("无可用优惠券");
                binding.tvTogetCoupons.setText("");
            } else if (coupons.size() == 1) {
                binding.tvSelecedDiscountCoupon.setText(coupons.get(0).getName());
                selectedCouponCode = coupons.get(0).getCode();
                binding.tvTogetCoupons.setText("领券");
                updateGoodsList(coupons);
                caculateGoodsAdapter.setCouponsBeans(coupons);

            } else {
                binding.tvSelecedDiscountCoupon.setText("请选择优惠券");
                binding.tvTogetCoupons.setText("领券");
                updateGoodsList(coupons);

            }
            if (addresses != null && !addresses.isEmpty()) {
                PrepareOrderBean.DataBean.AddressesBean addressesBean = addresses.get(0);
                addressId = addressesBean.getId();
                binding.rlAddReceiver.setVisibility(View.GONE);
                binding.addressContainer.setVisibility(View.VISIBLE);
                binding.addressName.setText(addressesBean.getContact_name());
                binding.addressTel.setText(addressesBean.getContact_phone());
                binding.addressDetail.setText(addressesBean.getAddress());
            } else {
                binding.rlAddReceiver.setVisibility(View.VISIBLE);
                binding.addressContainer.setVisibility(View.GONE);
            }
        }

    }

    private void updateGoodsList(List<PrepareOrderBean.DataBean.CouponsBean> coupons) {
        for (CartGoods bean : cartGoodsList) {
            for (PrepareOrderBean.DataBean.CouponsBean coupon : coupons) {
                boolean hasCoupon = false;
                int id = bean.getId();
                List<Integer> product = coupon.getProduct();
                for (Integer cpid : product) {
                    if (id == cpid) {
                        hasCoupon = true;
                    }
                }
                if (hasCoupon) {
                    bean.setCouponsBean(coupon);
                }

            }
        }
    }

}
